<template>
    <view >
        <view style="display: none;position: fixed;left: 50%;top: 50%;">{{ $store.state.hackUpdate }}</view>
        <load-more status="loading" v-if="initializing" />
        <chat-panel :storeKey="storeKey" :sending="sending" :sendingdata="sendingdata" @click-avatar="openProfile"
            @setSending="setSending" :boardheight="boardheight" ref="panel" />
        <v-sender v-if="!initializing" v-model="message" :userID="userID" @send="sendTextMessage" @face="sendVoice"
            @sendImage="sendImg" @sendVedio="sendVedio" @emoji="sendEmoji" @input="inputMessage"
            @handleEmotion="handleEmotion" @senderheight="set_sheight" @keyboardheight="keyboardheight"
            @getCall="getCall" :showboard="showboard" :sendtype="type" :isgroup="0" :groupid="friend.id" />
    </view>
</template>


<script>
    import {
        mapState,
        mapGetters
    } from 'vuex';
    import ChatPanel from '../../components/chat-panel.vue';
    import api from '../../library/index.js';
    import http from '../../library/http.js';
    import config from '../../config.js';
    import utils from "@/library/common.js"
    const GoEasy = uni.$GoEasy;
    const GRTC = uni.$GRTC;

    export default {
        components: {
            ChatPanel
        },
        data() {
            return {
                friend: {},
                message: '',
                initializing: false,
                getPick: false,
                showPickMoney: '',
                pickMsg: '',
                pickId: '',
                pickSender: {},
                pickTitle: '',
                pickErrorText: '',
                storeKey: '',
                redpackInfo: {},
                sending: false,
                sendingdata: [],
                senderheight: 120,
                sender: [],
                receiver: [],
                inpuvalue: '',
                boardheight: 0,
                showboard: false,
                type: '',
                user: uni.getStorageSync('userInfo'),
                system: uni.getStorageSync('system'),
                exclusiveSendData: {},
                text: '',
                userID: "",
                indexCall:0
            };
        },
        onLoad(opts) {
            this.text = opts.nickname
            this.userID = opts.id

            // #ifdef APP-PLUS  
            let currentWebview = this.$mp.page.$getAppWebview();
            currentWebview.setStyle({
                titleNView: {
                    titleText: ''
                },
            })
            // #endif
            this.friend = opts;

            this.storeKey = 'U' + this.friend.id;
            uni.setStorageSync('cache_key', this.storeKey);

            this.getUserInfo(this.friend.id);
            this.sender = this.user;
            this.receiver = this.friend;
            let vm = this
            uni.$on('exclusive', function(data) {
                console.log('exclusiveexclusive', data)
                vm.commitMessage('exclusive', data);
            })
        },
        onUnload() {
            // 离开页面时清空聊天记录
            console.log('离开页面时清空聊天记录')
            this.$store.commit('clearMessages');
            uni.setStorageSync('cache_key', '');
        },

        methods: {
            // 拨打电话
            getCall(data) {
                console.log('拨打电话', data)
                let _this = this;
                this.indexCall = this.indexCall + 1
                console.log('这是第几次',this.indexCall)
                if(this.indexCall == 1){
                    GRTC.end()
                    GRTC.call({
                        calleeId: this.userID,
                        mediaType: 0,
                        notification: {
                            title: this.user.nickname,
                            body: '邀请你语音通话',
                            sound: 'ring',
                            badge: '+1'
                        },
                    }).then(() => {
                        // utils.playAudios('/static/voice/wx.mp3');
                        uni.navigateTo({
                            url: `/pages/rtc/private/dial`,
                        })
                        this.indexCall = 0
                    }).catch((error) => {
                        console.log("呼叫失败:", error);
                        GRTC.end()
                        this.indexCall = 0
                        uni.showToast({
                           icon: "none",
                           title: '对方忙线中',
                           duration: 2000
                       })
                    })
                } else {
                    GTRC.end()
                    this.indexCall = 0
                }
                
            },
            // 检测输入值
            inputMessage(e) {
                this.emotion = e;
            },
            // 
            getUserInfo(id) {
                if (id > 0) {

                    id = parseInt(id);
                    http.setWait(false).get('user.php?act=userdetail', {
                        id: id,
                        group_id: 0,
                        userid: this.user.id
                    }).then(res => {
                        this.friend = res.data;
                        this.text = this.friend.nickname + `(${this.friend.isonline == 1?'在线':'离线'})`
                        uni.setNavigationBarTitle({
                            title: this.text
                        });
                    }).catch(() => {
                        uni.setNavigationBarTitle({
                            title: this.text
                        });
                    })


                } else {
                    var avatar = this.system.admin_logo;
                    if (avatar.indexOf('http') <= -1) avatar = config.imgUri + avatar;
                    this.friend = {
                        id: 0,
                        nickname: this.system.admin_nickname,
                        avatar: avatar
                    };

                }

            },
            toHtml(str) {
                str = str.replace(/ /g, "&nbsp;");
                str = str.replace(/\n/g, "<br>");
                return str;
            },
            set_sheight(e) {
                this.$refs.panel.setAutoHeight(e);
            },
            keyboardheight(e) {
                this.boardheight = e;

                this.$refs.panel.setAutoHeight(0);
            },

            // 选择表情
            handleEmotion(value) {
                //  console.log(value);
                this.emotion = value;
                this.type = 'emotion';
            },
            sendEmoji(e) {
                this.commitMessage('face', e);
            },
            sendImg(e) {
                console.log('--------------------------', e)
                this.commitMessage('image', e);
            },
            sendVedio(e) {
                this.commitMessage('vedio', e);
            },

            // 发送文本消息
            sendTextMessage() {
                this.emotionInfo = {
                    "type": "emotion",
                    "value": this.emotion,
                    "content": this.emotion
                }
                if (this.type == "emotion") {
                    this.commitMessage('emotion', this.emotionInfo);
                } else {
                    var msg = this.toHtml(this.message);
                    console.log('发送文本消息', msg, 'this.type', this.type)
                    uni.pageScrollTo({
                    	scrollTop: 2000000,
                    	duration: 0
                    })
                    this.commitMessage('text', msg);
                    this.goEasy.pubsub.publish({
                        channel: this.friend.id,  //请确认与接收端一致
                        message: msg,
                        qos: 1,//app内onMessage收到的消息内容
                        notification: { //定义通知栏推送
                            title: '您有一条新消息', //通知栏提醒标题，仅显示于通知栏
                            body:msg, //通知栏提醒内容，仅显示于通知栏
                            badge: "+1", //角标，值必须有引号，"0"表示该消息不需要设置角标，"+1"表示角标+1，不支持其他值， 默认为“0”
                        },
                        onSuccess: function () {
                            console.log("推送消息时设置角标 successfully.")
                        },
                        onFailed: function (error) {
                            console.log("推送消息时设置角标 to publish message, code:" + error.code + ' error:' + error.content);
                        }
                    });
                }
            },

            setSending(e) {

                this.sending = e;

            },

            commitMessage(type, sendData) {
                this.message = '';
                  this.showboard=true
                // console.log('commitMessage')
                if (type == 'image') {
                    var mid = sendData.mid;
                    sendData = sendData.src;
                } else if (type == 'vedio') {
                    var mid = sendData.mid;
                    //  sendData=sendData.src;
                } else if (type == 'voice') {
                    var mid = sendData.mid;
                } else {
                    var mid =
                        'm' +
                        Math.random()
                        .toString(36)
                        .substring(2);
                }

                let data = {
                    userid: this.user.id,
                    friend_uid: this.friend.id,
                    type: 'chat',
                    msgtype: type,
                    content: sendData,
                    mid: mid
                };
                //    console.log(data);

                var sendlocal = 0;
                if ((type == 'image' && sendData.indexOf('http') <= -1) || (type == 'vedio' && sendData.src.indexOf(
                        'http') <= -1) || (type == 'voice' && sendData.url.indexOf('http') <= -1)) {
                    //本地图片不发到服务器  

                    sendlocal = 1;
                } else {
                    this.$socket.send(data);

                }
                var that = this;
                if (type !== 'image' && type !== 'voice') {
                    var arr = {};
                    arr.id = that.receiver.id;
                    arr.cache_key = 'U' + arr.id;
                    arr['self'] = 1;
                    arr['isloading'] = 1;
                    arr['receiver_id'] = arr['id'];
                    arr['sender_id'] = that.sender.id;
                    arr['group_id'] = 0;
                    arr['timestamp'] = parseInt(new Date().getTime() / 1000);
                    arr['time'] = '';
                    arr['message'] = {
                        type: type,
                        content: sendData
                    };
                    arr['sender'] = that.sender;
                    arr['receiver'] = that.receiver;
                    arr['nickname'] = that.sender.nickname;
                    arr['avatar'] = that.sender.avatar;
                    arr['msg_id'] = '';
                    arr['_mid'] = mid;
                    that.sendingdata = arr;
                    that.sending = true;
                    this.type = 'text';
                    //that.sendmsg(arr);
                    // console.log(sendlocal，);
                }

                //that.sending=true;
            },

            sendVoice(e) {
                this.commitMessage('voice', e);
            },
            openProfile(e) {
                //     console.log(JSON.stringify(e));
                let params = {
                    id: e.id,
                    status: 'friend'
                };
                return this.$jump('friend.detail', params);
            }
        },
        onNavigationBarButtonTap(e) {
            let params = {
                ...this.friend,
                status: 'friend'
            };
            return this.$jump('friend.userset', params);
        }
    };
</script>

<style lang="scss">
    $avatar-width: 80upx;
    $control-height: 100upx;
    $control-input-height: $control-height - $uni-spacing-col-base * 2;

    page{
        background: #fff;
    }
    .placeholder {
        width: 750upx;
        height: 1upx;
    }

    .message {
        &-time {
            color: #999;
            font-size: 24upx;
            text-align: center;
        }

        &-info {
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: flex-start;
            padding: $uni-spacing-col-lg $uni-spacing-row-lg;

            .spacing {
                width: $uni-spacing-row-lg;
                height: $avatar-width;
                position: relative;
                display: flex;
                flex-direction: column;
                align-items: center;
                justify-content: center;
                flex-shrink: 0;

                &::before {
                    display: block;
                    content: '';
                    border: $uni-spacing-row-lg/2 solid transparent;
                    border-right-color: #fff;
                }
            }
        }

        &.right &-info {
            flex-direction: row-reverse;
            padding-left: $uni-spacing-row-lg;
            padding-right: $uni-spacing-row-lg * 2 + $avatar-width;

            .spacing::before {
                border-right-color: transparent;
                border-left-color: $uni-color-primary;
            }
        }

        &.right &-info {
            padding-left: $uni-spacing-row-lg * 2 + $avatar-width;
            padding-right: $uni-spacing-row-lg;
        }

        &-avatar {
            width: $avatar-width;
            height: $avatar-width;
            vertical-align: middle;
            border-radius: $uni-border-radius-base;
            flex-shrink: 0;
        }

        &-content {
            font-size: 32upx;
            background: rgba(255, 255, 255, 1);
            border-radius: $uni-border-radius-base;
        }

        &.right &-content {
            color: white;
            background-color: $uni-color-primary;
        }

        &--text &-content {
            padding: 20upx $uni-spacing-row-base;
        }

        &-failed {
            width: 30upx;
            height: 30upx;
            background-color: $uni-color-error;
            border-radius: 50%;
            margin: ($avatar-width - 30upx)/2 $uni-spacing-row-base 0;
        }
    }
</style>